<template>
  <div class="container">
    <el-card class="content">
      <!-- 标题区域 -->
      <div class="header">
        <el-button type="primary" class="btn">{{
          judgeEmpty("typeSort")
        }}</el-button>
        <h1>{{ articleInfo && articleInfo.title }}</h1>
        <div class="author">
          <img src="@/assets/images/avatar.webp" class="author_pic" />

          <div class="author_info">
            <h4>文一</h4>
            <div class="labels">
              <span class="label"
                ><el-icon color="#bedd10"><View /></el-icon
                ><span class="text">阅读</span>{{ 0 }}</span
              >
              <span class="split-icon">/</span>
              <span class="label"
                ><el-icon color="#26d399"><ChatDotRound /></el-icon
                ><span class="text">评论</span>{{ 0 }}</span
              >
              <span class="split-icon">/</span>

              <span class="label"
                ><el-icon color="#ec7d62"><Star /></el-icon
                ><span class="text">收藏</span>{{ collectNum }}</span
              >
              <span class="split-icon">/</span>

              <span class="label"
                ><svg-icon
                  name="dianzan"
                  width="12"
                  height="12"
                  class="svg"
                  color="#26d399"
                ></svg-icon
                ><span class="text">赞</span>{{ zanNum }}</span
              >
              <span class="split-icon">/</span>

              <span class="label"
                ><el-icon color="#ec7d62"><Clock /></el-icon>{{ "3天前" }}</span
              >
            </div>
          </div>
        </div>
      </div>
      <!-- 温馨提示区域 -->
      <div class="tip">
        <div class="top">
          <svg-icon name="tip" color="#50bfff" class="svg"></svg-icon>温馨提示：
        </div>
        <p>
          本着开源共享、共同学习的精神，若内容或图片失效，请留言反馈。若有内容不小心影响到您的利益，请联系博主删除
        </p>
      </div>
      <!-- md文档区域 -->
      <template v-if="articleInfo">
        <v-md-preview
          :text="articleInfo.contentMd"
          v-highlight
          ref="preview"
        ></v-md-preview>
      </template>
      <!-- 发表评论 -->

      <!-- 评论列表 -->
      <CommentNews :id="id" v-if="id"/>
    </el-card>
    <div class="right">
      <usercenter />
      <el-card class="title-list">
        <h3>目录</h3>
        <div class="list">
          <div
            v-for="anchor in titleList"
            :style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }"
            @click="handleAnchorClick(anchor)"
            class="title-item"
          >
            <a style="cursor: pointer">{{ anchor.title }}</a>
          </div>
        </div>
      </el-card>
    </div>
    <SideBar
      :articleId="id"
      :articleInfo="articleInfo"
      @getInfo="getList"
      :dianzanStatus="dianzanStatus"
      :collectStatus="collectStatus"
      @changeStatus="handleChangeStatus"
    />
  </div>
</template>
<script setup>
import { useRoute } from "vue-router";
import { ref, onMounted, reactive, nextTick, computed } from "vue";
import { getArticleInfo } from "@/api/article.js";
import usercenter from "../home/user/usercenter.vue";
import { useStore } from "vuex";
import SideBar from "./SideBar.vue";
import Comment from "./Comment.vue";
import CommentNews from "./CommentNews.vue"
const id = ref();
const preview = ref();
const articleInfo = ref();
const Route = useRoute();
let titleList = ref([]);
let $store = useStore();
let dianzanStatus = ref(false);
let collectStatus = ref(false);

let zanNum = computed(() => {
  if (articleInfo.value) {
    let ids =
      (articleInfo.value.dianzanIds &&
        articleInfo.value.dianzanIds
          .split(",")
          .filter((item) => item !== "")) ||
      [];
    console.log(ids, "ids");
    return ids.length;
  } else {
    return 0;
  }
});
let collectNum = computed(() => {
  if (articleInfo.value) {
    let ids =
      (articleInfo.value.collectIds &&
        articleInfo.value.collectIds
          .split(",")
          .filter((item) => item !== "")) ||
      [];
    console.log(ids, "collecgtids");

    return ids.length;
  } else {
    return 0;
  }
});

onMounted(() => {
  getInfo();
});

const getList = () => {
  console.log("hhhh@@@@@@@");
  getInfo();
};

const handleChangeStatus = (type) => {
  console.log("type");
  if (type == "dianzan") {
    dianzanStatus.value = !dianzanStatus.value;
  } else {
    collectStatus.value = !collectStatus.value;
  }
};

const getStatus = (ids) => {
  console.log(ids, "测试ids");
  let arr = (ids && ids.split(",")) || [];
  let flag = arr.find((item) => item === userId.value + "");
  if (flag) {
    return true;
  } else {
    return false;
  }
};

let userId = computed(() => {
  return $store.state.user.userInfo.id;
});

// 请求获取webinfo信息
const getInfo = async () => {
  id.value = Route.params.id;
  console.log(id,"id变化了")
  let res = await getArticleInfo(id.value);
  articleInfo.value = res.data;
  console.log(articleInfo.value, "arti");
  dianzanStatus.value = getStatus(articleInfo.value.dianzanIds);
  collectStatus.value = getStatus(articleInfo.value.collectIds);

  console.log(dianzanStatus.value, collectStatus.value, "statrus");
  // 等下一轮dom渲染才获取到ref
  nextTick(() => {
    handleAnchor();
  });
};

const judgeEmpty = (key) => {
  if (articleInfo.value && articleInfo.value[key]) {
    if (key === "typeSort")
      return articleInfo.value[key].typeName || "暂无分类";
    return articleInfo.value[key];
  } else {
    return "暂无分类";
  }
};

// 处理自定义锚点需要的数组
const handleAnchor = () => {
  if (preview.value) {
    console.log(preview, "preview");
    const anchors = preview.value.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");
    if (anchors) {
      const arr = Array.from(anchors).filter(
        (title) => title.innerText.trim() != ""
      );
      console.log(arr, "dom");
      if (!arr.length) {
        titleList.value = [];
        return;
      }
      const Htags = Array.from(
        new Set(arr.map((title) => title.tagName))
      ).sort();
      // 拿到h1-h6 md文档中包含的h标签，并去重并且排序
      console.log(Htags, "name");
      titleList.value = arr.map((el) => ({
        title: el.innerText,
        lineIndex: el.getAttribute("data-v-md-line"),
        indent: Htags.indexOf(el.tagName),
      }));
    }
  }

  console.log("---", titleList.value);
};

// v-md-editor的自定义锚点
const handleAnchorClick = (anchor) => {
  const { lineIndex } = anchor;

  const heading = preview.value.$el.querySelector(
    `[data-v-md-line="${lineIndex}"]`
  );

  if (heading) {
    preview.value.scrollToTarget({
      target: heading,
      scrollContainer: window,
      top: 70,
    });
  }
};
</script>
<style lang="scss" scoped>
:deep .el-card__body {
  padding: 0;
}
:deep .github-markdown-body {
  padding: 10px;
}

.container {
  display: flex;
  justify-content: center;

  // 内容区域
  .content {
    padding: 20px;
    background-color: #fff;
    width: 50%;
    margin-top: 60px;
    // 标题区域
    .header {
      .btn {
        transition: all 0.8s;
        &:hover {
          transform: translateY(-5px);
          background: #409eff;
        }
      }
      h1 {
        font-size: 24px;
        text-align: center;
        line-height: 50px;
      }

      .author {
        border-bottom: 1px solid #e4e7ed;
        padding-bottom: 20px;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        position: relative;
        &::after {
          position: absolute;
          content: "";
          left: 0;
          bottom: 0;
          width: 10%;
          height: 2px;
          background-color: $strong;
        }
        .author_pic {
          box-sizing: content-box;
          padding: 3px;
          border-radius: 50%;
          border: 1px solid $strong;
          width: 40px;
          height: 40px;
          margin-right: 10px;
        }
        .author_info {
          flex: 1;
          .labels {
            color: #909399;
          }
          .label {
            line-height: 16px;
            font-size: 14px;
            vertical-align: -4px;
            margin-right: 10px;

            .text {
              margin-left: 5px;
              margin-right: 5px;
            }
            .el-icon {
              vertical-align: -2px;
            }
          }
          .split-icon {
            vertical-align: -4px;
            margin-right: 10px;
          }
          .svg {
            display: inline-block;
          }
        }
      }
    }
    .tip {
      .svg {
        display: inline-block;
        vertical-align: -2px;
        margin-right: 5px;
      }
      margin-bottom: 20px;
      border-radius: 5px;
      padding: 10px;
      color: #888;
      background-color: #ecf8ff;
      border-left: 5px solid #50bfff;
      p {
        margin-top: 5px;
        text-indent: 2em;
      }
    }
  }
  .right {
    position: sticky;
    top: 70px;
    width: 20%;
    height: 100vh;
    margin-top: 60px;
    // background-color: #fff;
    margin-left: 20px;
    .user {
      margin-bottom: 20px;
      background-color: #fff;
      height: 100px;
    }
    .title-list {
      h3 {
        padding: 20px 15px;
        border-bottom: 1px solid #e4e7ed;
      }
      .title-item {
        cursor: pointer;
        &:hover {
          background: #ecf5ff;
          a {
            color: $strong;
          }
        }
      }
    }
  }
}
</style>
